import { app, BrowserWindow, ipcMain, dialog, session, shell } from 'electron/main'
import { spawn, execSync } from 'child_process'
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import portfinder from 'portfinder';
import CDP from 'chrome-remote-interface'
import EventEmitter from "events";
import net from "net";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const WebSocket = require('ws');

class ChromeController extends EventEmitter {
    constructor(options = {}) {
        super();
        this.process = null
        this.profilePath = null
        this.debugPort = 0
        this.userDataDir = app.getPath('userData')
        this.browserParams = {}
        this.win = null
        this.launchArgs = {}
    }

    async launch(win, data) {
        this.win = win
        this.browserParams = data
        if (this.process) {
            throw new Error('Chrome instance already running')
        }

        // 准备运行环境
        await this._prepareEnvironment()

        // 启动浏览器进程
        await this._startBrowserProcess()

        try {
            // 等待端口就绪
            await this._waitForPortReady()
            // 初始化CDP控制
            await this._initializeCDP()
        } catch (error) {
            console.log(error);

        }
    }

    async _prepareEnvironment() {
        // 创建用户目录
        this.profilePath = path.join(
            this.userDataDir,
            `sdk/profile/chrome-profile-${this.browserParams.fingerprint_id}`
        )
        // await fs.ensureDir(this.profilePath)
        const exists = await fs.pathExists(this.profilePath)
        if (!exists) {
            await fs.ensureDir(this.profilePath)
        }

        // 获取调试端口
        this.debugPort = await portfinder.getPortPromise({
            port: 9222 + this.browserParams.id,
            stopPort: 9322 + this.browserParams.id
        })
    }



    async _startBrowserProcess() {
        // 生成启动参数
        await this._getlaunchArgs()
        // 启动前生成全局权限配置
        await this._setGlobalPermissions();


        console.log(this.launchArgs);

        this.process = spawn(this.browserParams.path, this.launchArgs, {
            detached: true,
            stdio: ['ignore', 'ignore', 'pipe']
        })


        // 监听进程错误
        this.process.on('error', err => {
            this.emit('error', new Error(`Process error: ${err.message}`))
        })

        // 捕获stderr输出
        this.process.stderr.on('data', data => {
            this.emit('debug', data.toString())
        })

        // 进程退出处理
        this.process.on('exit', code => {
            this.emit('terminated', { code })
            this._cleanup()
        })

    }

    async _getlaunchArgs() {
        const launchArgs = [
            `--user-data-dir=${this.profilePath}`,
            `--remote-debugging-port=${this.debugPort}`,
            `--timezone=America/New_York`
        ]

        // 语言
        if (this.browserParams.hign.language != '') {
            launchArgs.push(`--lang=${this.browserParams.hign.language}`)
        }
        // 时区
        if (this.browserParams.hign.timeZone != '') {
            launchArgs.push(`--timezone=${this.browserParams.hign.timeZone}`)
        }

        // 地理位置
        if (this.browserParams.hign.location.show == 0) {
            launchArgs.push(`--disable-geolocation`)
        }

        // 分辨率
        if (this.browserParams.hign.resolution != '') {
            launchArgs.push(`--window-size=${this.browserParams.hign.resolution.resolutionW},${this.browserParams.hign.resolution.resolutionH}`)
            launchArgs.push(`--high-dpi-support=1`)
        }


        // 经纬度
        if (this.browserParams.hign.location.show == 1 && this.browserParams.hign.location.type == 1) {
            launchArgs.push(`--geolocation-override=${this.browserParams.hign.location.latitude},${this.browserParams.hign.location.longitude},${this.browserParams.hign.location.accuracy}`)
        }


        // 禁止加载图片
        if (this.browserParams.hign.loadingImg == 1) {
            // launchArgs.push(`--blink-settings=imagesEnabled=false`)
        }
        // 禁止加载视频
        if (this.browserParams.hign.loadingVide == 1) {
            launchArgs.push(`--disable-video`)
            launchArgs.push(`--disable-video-capture`)
            launchArgs.push(`--disable-accelerated-video`)
            launchArgs.push(`--disable-accelerated-video-decode`)
            launchArgs.push(`--disable-accelerated-video-encode`)
            launchArgs.push(`--disable-threaded-video-decode`)
            launchArgs.push(`--disable-features=LiveCaption,MediaRouter`)
        }
        // 禁止播放声音
        if (this.browserParams.hign.loadingMusic == 1) {
            launchArgs.push(`--mute-audio`)
        }
        // 网页通知
        if (this.browserParams.hign.webNotice == 1) {
            launchArgs.push(`--disable-notifications`)
        }

        // 自定义启动参数
        if (this.browserParams.hign.startParams.length > 0) {
            this.browserParams.hign.startParams.forEach(item => {
                launchArgs.push(item)
            });
        }

        // 开启端口扫描保护
        if (this.browserParams.hign.portProtect.type == 1) {
            if (this.browserParams.hign.portProtect.ports.length > 0) {
                launchArgs.push(`--restricted-ports=${this.browserParams.hign.portProtect.ports.join(',')}`)
            } else {
                launchArgs.push(`--restricted-ports=1-65535`)
            }
        }

        if (this.browserParams.hign.media == 0) {
            launchArgs.push(`--use-fake-device-for-media-stream`)
            launchArgs.push(`--use-fake-ui-for-media-stream`)
        }

        const isDev = !app.isPackaged;
        let extensionPath;
        if (isDev) {
            extensionPath = path.resolve('./extensions');
        } else {
            // 生产环境：插件会被打包到应用资源目录（如 resources）
            extensionPath = path.join(__dirname, '../../extensions');
        }
        launchArgs.push(`--load-extension=${extensionPath}`)

        this.launchArgs = launchArgs
    }

    // 设置数据文件
    async _setGlobalPermissions() {
        const prefsPath = path.join(this.profilePath, 'Default');
        const exists = await fs.pathExists(prefsPath)
        if (!exists) {
            await fs.ensureDir(prefsPath)
        }
        const prefs = {
            profile: {
                default_content_setting_values: {
                }
            }
        };

        // 禁止地理位置
        if (this.browserParams.hign.location.show == 0) {
            prefs.profile.default_content_setting_values.geolocation = 2
        }
        // 禁止播放声音
        if (this.browserParams.hign.loadingMusic == 1) {
            prefs.profile.default_content_setting_values.sound = 2
        }
        // 禁止播放视频
        if (this.browserParams.hign.loadingVide == 1) {
            prefs.profile.default_content_setting_values.media_stream_video = 2
            prefs.profile.default_content_setting_values.media_playback_requires_user_gesture = true
        }
        const prefsPath2 = path.join(prefsPath, 'Preferences');
        // this.getfsData('C:/Users/admin/AppData/Roaming/hubstudio-client/sdk/cache/chromium_1916081121635782656/Default', 'Preferences')
        await fs.promises.writeFile(prefsPath2, JSON.stringify(prefs));
    }


    async _waitForPortReady(timeout = 6000) {
        return new Promise((resolve, reject) => {
            const startTime = Date.now()

            const checkPort = () => {

                const socket = net.connect(this.debugPort, '127.0.0.1')

                socket.on('connect', () => {
                    socket.destroy()
                    resolve()
                })

                socket.on('error', (err) => {
                    if (Date.now() - startTime > timeout) {
                        reject(new Error(`端口 ${this.debugPort} 未就绪，超时 ${timeout}ms`))
                    } else {
                        setTimeout(checkPort, 500)
                    }
                })
            }

            checkPort()
        })
    }

    async _initializeCDP() {
        try {
            const client = await CDP({ port: this.debugPort });
            this._cdpClient = client;

            setTimeout(() => {

            }, 3000);
            client.Runtime.enable()

            setTimeout(() => {
                // let contextId = this.connectAndGetContextId(client)
                // console.log(contextId);
            }, 3000);




            // 全局UA设置（主目标）
            await client.Network.setUserAgentOverride({
                userAgent: this.browserParams.setting.userAgent,
                platform: this.browserParams.deviceType
            });

            this._tabClients = new Map();

            // 强化事件监听：在绑定监听器后再获取初始标签页
            client.Target.setDiscoverTargets({ discover: true });

            // 监听动态目标创建（包含未来所有新页面）
            client.Target.on('targetCreated', async ({ targetInfo }) => {

                if (this._isValidTarget(targetInfo)) {
                    await this._handleNewTarget(targetInfo);
                }
            });

            // 监听目标销毁
            client.Target.on('targetDestroyed', ({ targetId }) => {
                console.log(targetId);

                this._cleanupTarget(targetId);
            });


            client.on('disconnect', () => {
                // 通过IPC通知Electron浏览器已关闭
                console.log('web Close');
                this.win.webContents.send('close-browser', {
                    fingerprint_id: this.browserParams.fingerprint_id
                })
            });


            // 处理现有标签页（延迟确保事件监听就绪）
            setTimeout(async () => {
                const { targetInfos } = await client.Target.getTargets();
                targetInfos.forEach(target => {
                    if (this._isValidTarget(target)) {
                        this._handleNewTarget(target);
                        this.connectToPlugin()
                    }
                });
            }, 500);
        } catch (err) {
            console.error('CDP初始化失败:', err);
        }
    }

    // 目标有效性校验
    _isValidTarget(targetInfo) {
        return (
            targetInfo.type === 'page' &&
            // targetInfo.url !== 'chrome://newtab/' && // 过滤新标签页占位
            !targetInfo.title.startsWith('DevTools') // 过滤开发者工具
        );
    }

    // 统一处理新目标
    async _handleNewTarget(targetInfo) {
        try {
            const tab = await CDP({ port: this.debugPort, target: targetInfo.targetId });
            this._tabClients.set(targetInfo.targetId, tab);
            await Promise.all([
                tab.Network.enable(),
                tab.Page.enable(),
                tab.Runtime.enable(),
                // tab.Browser.enable(),
                // tab.Browser.enable().catch(() => { })
            ]);

            let data2 = {
                action: 'GET_ENVIRONMENT_PRINT_ID',
                ENVIRONMENT_PRINT_ID: this.browserParams.id
            }


            await tab.send('Page.addScriptToEvaluateOnNewDocument', {
                source: `
                  (function() {
                    setTimeout(() => {
                        console.log('11111bbbbb');
                        window.ENVIRONMENT_PRINT_ID = ${this.browserParams.id};
                    }, 1000);

                  })();
                `
            });

            await this._applyNetworkConfig(tab);


            // 地理位置自定义经纬度
            if (this.browserParams.hign.location.show == 1 && this.browserParams.hign.location.type == 1) {
                await this._setLocation(tab, targetInfo)
            }
            // 分辨率
            if (this.browserParams.hign.resolution.name != '') {
                await this._setResolution(tab, targetInfo)
            }
            // 字体
            if (this.browserParams.hign.font.type == 0) {
                await this._setFont(tab, targetInfo)
            }
            // 字体指纹
            await this._setFontprint(tab, targetInfo)
            // WebRTC
            // await this._setWebrtc(tab, targetInfo)

            // 电池
            await this._setBattery(tab, targetInfo)
            // Do not track
            await this._setDonottrack(tab, targetInfo)

            // 禁止加载视频
            if (this.browserParams.hign.loadingVide == 1) {
                await this._setVideo(tab, targetInfo)
            }

            // 设备内存数
            if (this.browserParams.hign.memory != 0) {
                await this._setMemorys(tab, targetInfo)
            }

            // 硬件并发数
            if (this.browserParams.hign.concurrency != 0) {
                await this._setConcurrency(tab, targetInfo)
            }

            // 媒体设备
            if (this.browserParams.hign.media == 0) {
                await this._setMedia(tab, targetInfo)
            }

            // SpeechVoices
            console.log(this.browserParams.hign.speechVoice);

            if (this.browserParams.hign.speechVoice == 0) {
                await this._setSpeechVoices(tab, targetInfo)
            }

            // 禁止加载图片
            if (this.browserParams.hign.loadingImg == 1) {
                await this._setBlockImagesWithSizeLimit(tab, this.browserParams.hign.imgSize)
            }


            // 网页通知
            if (this.browserParams.hign.webNotice == 1) {
                await this._setNotice(tab, targetInfo)
            }



            // 监听页面导航事件（应对动态内容）
            tab.Page.on('frameNavigated', () => {
                this._configureNewTab(tab); // 每次导航后重新应用配置
            });

            await this._configureNewTab(tab);

            await this.injectGlobalVariable(tab)
        } catch (err) {
            console.error(`目标处理失败 [${targetInfo.targetId}]:`, err);
        }
    }


    // 统一应用网络配置
    async _applyNetworkConfig(client) {
        try {
            let detail = {
                userAgent: this.browserParams.setting.userAgent,
                platform: this.browserParams.deviceType,
                userAgentMetadata: this.browserParams.setting.userAgentMetadata
            }

            if (this.browserParams.hign.language != '') {
                detail.acceptLanguage = `${this.browserParams.hign.language};q=0.9`
            }
            // 设置完整UA和平台信息

            await client.Network.setUserAgentOverride(detail);

            // 设置额外请求头
            await client.Network.setExtraHTTPHeaders({
                headers: {
                    'X-Operating-System': this.browserParams.deviceType,
                    'Sec-CH-UA-Platform': `"${this.browserParams.deviceType}"` // 现代浏览器头
                }
            });

            // 验证请求头（调试用）
            client.Network.on('requestWillBeSent', event => {
                // console.log('验证请求头:', {
                //     ua: event.request.headers['User-Agent'],
                //     platform: event.request.headers['Sec-CH-UA-Platform']
                // });
            });
        } catch (err) {
            console.error('网络配置失败:', err);
        }
    }

    // 清理目标资源
    async _cleanupTarget(targetId) {
        const tab = this._tabClients.get(targetId);
        if (tab) {
            await tab.close().catch(() => { });
            this._tabClients.delete(targetId);
            console.log(`已清理目标: ${targetId}`);
        }
    }

    async _configureNewTab(tabClient) {
        try {
            // 原子化配置操作
            await Promise.all([
                tabClient.Network.enable(),
                tabClient.Page.enable(),
                tabClient.Network.setCacheDisabled({ cacheDisabled: true }),
                tabClient.Network.setUserAgentOverride({
                    userAgent: this.browserParams.setting.userAgent,
                    platform: this.browserParams.deviceType
                }),
                tabClient.Page.setLifecycleEventsEnabled({ enabled: true })
            ]);

            // 添加DOM加载监听
            tabClient.Page.on('domContentEventFired', () => {
                // this._injectCustomLogic(tabClient); // 自定义逻辑注入点
            });
        } catch (err) {
            console.error('标签页配置失败:', err);
        }
    }

    async terminate() {
        if (!this.process) return

        // try {
        //     process.kill(-this.process.pid, 'SIGTERM')
        //     await this._cleanup()
        //     this.emit('terminated', { code: 0 })
        // } catch (err) {
        //     this.emit('error', new Error(`终止进程失败: ${err.message}`))
        // }

        try {
            if (process.platform === 'win32') {
                // Windows 使用 taskkill 终止进程树

                try {
                    execSync(`taskkill /pid ${this.process.pid} /f /t`);
                } catch (error) {
                    // 进程可能已退出，忽略错误
                }
            } else {
                // macOS/Linux 终止整个进程组
                try {
                    process.kill(-this.process.pid, 'SIGTERM');
                } catch (error) {
                    // 进程可能已退出，忽略错误
                }
            }

            await this._cleanup();
            this.emit('terminated', { code: 0 });
        } catch (err) {
            this.emit('error', new Error(`终止进程失败: ${err.message}`));
        }
    }


    // 地理位置自定义经纬度
    async _setLocation(tab, targetInfo) {
        const latitude = this.browserParams.hign.location.latitude;
        const longitude = this.browserParams.hign.location.longitude;
        const accuracy = this.browserParams.hign.location.accuracy;
        await tab.Emulation.setGeolocationOverride({
            latitude,
            longitude,
            accuracy
        });

    }

    // 设置分辨率
    async _setResolution(tab, targetInfo) {
        const width = parseFloat(this.browserParams.hign.resolution.resolutionW);
        const height = parseFloat(this.browserParams.hign.resolution.resolutionH);
        const { bounds } = await tab.Browser.getWindowForTarget({
            targetId: targetInfo.targetId
        });
        await tab.Emulation.setDeviceMetricsOverride({
            width: bounds.width,
            height: bounds.height,
            deviceScaleFactor: 2,
            mobile: false,
            screenWidth: width,
            screenHeight: height,
            screenOrientation: { angle: 0, type: 'landscapePrimary' }
        });
    }

    // 字体
    async _setFont(tab, targetInfo) {
        try {
            // 现代API
            if (typeof tab.Emulation.setFontFamilies === 'function') {
                await tab.Emulation.setFontFamilies({
                    fontFamilies: {
                        standard: this.browserParams.hign.font.font.join(','),
                        sansSerif: this.browserParams.hign.font.font.join(',')
                    }
                });
            }

            // 强制CSS注入
            await tab.Runtime.evaluate({
                expression: `
                    (() => {
                        const style = document.createElement('style');
                        style.id = 'font-override';
                        style.textContent = \`
                            * {
                                font-family: "${this.browserParams.hign.font.font[0]}" !important;
                            }
                        \`;
                        document.head.prepend(style);
                    })()
                `
            });


        } catch (err) {
            console.error('字体设置失败:', err);
        }
    }

    // 字体指纹
    async _setFontprint(tab, targetInfo) {
        const FINGERPRINT_MODE = this.browserParams.hign.fontprint

        await tab.Runtime.evaluate({
            expression: `
                // 保存原始方法引用
                const originalGetComputedStyle = window.getComputedStyle;
                
                // ====== 代理模式劫持 ======
                window.getComputedStyle = function(element, pseudoElt) {
                    const styles = originalGetComputedStyle(element, pseudoElt);
                    
                    // 创建样式代理
                    return new Proxy(styles, {
                        get(target, prop) {
                            if (prop === 'fontFamily') {
                                return ${FINGERPRINT_MODE === 'NOISE'} 
                                    ? 'NoiseFont-' + Math.random().toString(36).substr(2, 4)
                                    : 'Arial, sans-serif';
                            }
                            return Reflect.get(target, prop);
                        },
                        set() { return true; } // 绕过写保护
                    });
                };
    
                // ====== 原生样式覆盖 ======
                const overrideFontStyle = () => {
                    document.querySelectorAll('*').forEach(el => {
                        if (!el.style.getPropertyValue('--font-override')) {
                            el.style.setProperty(
                                'font-family', 
                                ${FINGERPRINT_MODE === 'NOISE'} 
                                    ? 'NoiseFont, ' + el.style.fontFamily 
                                    : 'Arial, sans-serif',
                                'important'
                            );
                            el.style.setProperty('--font-override', 'true');
                        }
                    });
                };
    
                // 初始执行
                overrideFontStyle();
    
                // 动态内容监听
                new MutationObserver(overrideFontStyle).observe(document, {
                    childList: true,
                    subtree: true,
                    attributes: true,
                    attributeFilter: ['style']
                });
    
                // ====== CSS OM 层劫持 ======
                const originalCSSGet = CSSStyleDeclaration.prototype.getPropertyValue;
                CSSStyleDeclaration.prototype.getPropertyValue = function(prop) {
                    if (prop === 'font-family') {
                        return ${FINGERPRINT_MODE === 'NOISE'} 
                            ? 'NoiseFont, ' + originalCSSGet.call(this, prop)
                            : originalCSSGet.call(this, prop);
                    }
                    return originalCSSGet.call(this, prop);
                };
            `
        });
    }

    // WebRTC
    async _setWebrtc(tab, targetInfo) {
        let targetIP = '172.17.131.239'
        // 1. 协议层配置
        try {
            await tab.send('Network.setWebRTCEncryption', { enabled: true });
        } catch (err) {
            console.warn('WebRTC 加密设置失败:', err);
        }

        // 2. JS 层劫持 (核心逻辑)
        await tab.Runtime.evaluate({
            expression: `
            (() => {
                const TARGET_IP = '${targetIP}';
                const originalRTCPeerConnection = window.RTCPeerConnection;
                
                // 完全覆盖 RTCPeerConnection
                window.RTCPeerConnection = function(config) {
                    const sanitizedConfig = {
                        ...config,
                        iceServers: (config?.iceServers || []).map(server => ({
                            ...server,
                            urls: server.urls.map(url => {
                                // 强制替换 STUN/TURN 地址
                                if(url.startsWith('stun:') || url.startsWith('turn:')) {
                                    return url.replace(
                                        /([0-9]{1,3}\\.){3}[0-9]{1,3}/, 
                                        TARGET_IP
                                    );
                                }
                                return url;
                            })
                        }))
                    };

                    const pc = new originalRTCPeerConnection(sanitizedConfig);

                    // 劫持 ICE 候选生成
                    const originalAddIceCandidate = pc.addIceCandidate.bind(pc);
                    pc.addIceCandidate = candidate => {
                        if (candidate && candidate.candidate) {
                            const modified = new RTCIceCandidate({
                                ...candidate,
                                candidate: candidate.candidate.replace(
                                    /([0-9]{1,3}\\.){3}[0-9]{1,3}/g,
                                    TARGET_IP
                                )
                            });
                            return originalAddIceCandidate(modified);
                        }
                        return originalAddIceCandidate(candidate);
                    };

                    // 修改 SDP 生成
                    pc.createOffer = new Proxy(pc.createOffer, {
                        apply: async (target, thisArg, args) => {
                            const offer = await Reflect.apply(target, thisArg, args);
                            return new RTCSessionDescription({
                                ...offer,
                                sdp: offer.sdp.replace(
                                    /([0-9]{1,3}\\.){3}[0-9]{1,3}/g, 
                                    TARGET_IP
                                )
                            });
                        }
                    });

                    // 实时候选拦截
                    pc.addEventListener('icecandidate', e => {
                        if (e.candidate) {
                            const fakeCandidate = new RTCIceCandidate({
                                ...e.candidate,
                                address: TARGET_IP,
                                relatedAddress: TARGET_IP,
                                port: 9 // 伪端口
                            });
                            pc.addIceCandidate(fakeCandidate);
                        }
                    });

                    return pc;
                };

                // 保持原型链
                RTCPeerConnection.prototype = originalRTCPeerConnection.prototype;

                // 劫持 getStats
                const originalGetStats = RTCPeerConnection.prototype.getStats;
                RTCPeerConnection.prototype.getStats = async function() {
                    const stats = await originalGetStats.call(this);
                    return Array.from(stats).map(stat => {
                        if (['local-candidate', 'remote-candidate'].includes(stat.type)) {
                            return { ...stat, ipAddress: TARGET_IP };
                        }
                        return stat;
                    });
                };
            })();
        `,
            userGesture: true
        });

        // 3. 持久化处理
        tab.Page.frameNavigated(() => {
            this._forceWebRTC(tab, targetIP); // 页面跳转后重新注入
        });
    }

    // 禁止网页通知
    async _setNotice(tab, targetInfo) {
        await tab.Browser.setPermission({
            origin: 'https://*/*',      // 仅匹配 HTTPS 协议的所有域名
            permission: { name: 'notifications' },
            setting: 'denied'
        });
        await tab.Page.addScriptToEvaluateOnNewDocument({
            source: `
              // 强制覆盖 Notification 权限
              Object.defineProperty(window, 'Notification', {
                value: {
                  permission: 'denied',
                  requestPermission: () => Promise.resolve('denied')
                },
                writable: false,
                configurable: false
              });
          
              // 覆盖权限查询接口
              const originalQuery = navigator.permissions.query;
              navigator.permissions.query = (params) => {
                if (params.name === 'notifications') {
                  return Promise.resolve({ state: 'denied' });
                }
                return originalQuery(params);
              };
            `
        });


    }

    // 禁止加载视频
    async _setVideo(tab, targetInfo) {

        // 设置全局拦截
        await tab.Network.setRequestInterception({
            patterns: [{
                urlPattern: '.*',
                resourceType: 'Media',
                interceptionStage: 'HeadersReceived'
            }]
        });

        // 动态拦截
        const requestHandler = async (event) => {
            try {
                const { interceptionId, request } = event;
                const contentType = request.headers['Content-Type'] || '';

                const isVideo = [
                    'video/mp4',
                    'video/webm',
                    'application/vnd.apple.mpegurl'
                ].some(type => contentType.includes(type));

                const opts = { interceptionId };
                if (isVideo) opts.errorReason = 'BlockedByClient';

                await tab.Network.continueInterceptedRequest(opts);
            } catch (error) {
                console.error('处理拦截失败:', error.message);
            }
        };
        tab.Network.on('requestIntercepted', requestHandler);

        // 注入脚本
        await tab.Page.addScriptToEvaluateOnNewDocument({
            source: `
        Object.defineProperty(HTMLMediaElement.prototype, 'play', {
            value: () => new Promise((_, reject) => 
                reject(new Error('VIDEO_BLOCKED')))
        });
        window.WebSocket = class BlockedWebSocket extends WebSocket {
            constructor(url) {
                if (/\.m3u8|\.ts/.test(url)) throw new Error('STREAM_BLOCKED');
                super(url);
            }
        }`
        });
    }

    // 禁止加载图片
    async _setBlockImagesWithSizeLimit(tab, MAX_IMAGE_SIZE_KB) {
        const blockedImageUrls = new Set();
        const requestMap = new Map();
        // 设置请求拦截，针对图片类型在响应头接收阶段拦截
        await tab.Network.setRequestInterception({
            patterns: [
                {
                    urlPattern: '*',
                    resourceType: 'Image',
                    interceptionStage: 'HeadersReceived' // 关键：在收到响应头后拦截
                }
            ]
        });

        tab.on('tab.Network.requestIntercepted', async (params) => {
            try {
                const { interceptionId, request, resourceType } = params;

                // 仅处理图片类型请求
                if (resourceType !== 'Image') {
                    await tab.Network.continueInterceptedRequest({ interceptionId });
                    return;
                }

                const imageUrl = request.url;

                // 立即拦截已拉黑的请求
                if (blockedImageUrls.has(imageUrl)) {
                    await tab.Network.continueInterceptedRequest({
                        interceptionId,
                        errorReason: 'BlockedByClient'
                    });
                    return;
                }

                // 非黑名单请求继续处理
                // 获取响应头并检查 Content-Length
                const responseHeaders = params.responseHeaders || [];
                const headersArray = Array.isArray(responseHeaders) ? responseHeaders : [];

                const contentLengthEntry = headersArray.find(entry =>
                    entry.name.toLowerCase() === 'content-length'
                );

                // 解析 Content-Length（优先使用头部信息）
                const headerSize = contentLengthEntry ?
                    parseInt(contentLengthEntry.value, 10) || 0 :
                    0;

                // 如果头部已超限，立即拦截
                if (headerSize > MAX_IMAGE_SIZE_KB * 1024) {
                    blockedImageUrls.add(imageUrl);
                    await tab.Network.continueInterceptedRequest({
                        interceptionId,
                        errorReason: 'BlockedByClient'
                    });
                    return;
                }

                // 未知大小请求放行 + 启动分块监控
                // 记录请求ID与URL的映射
                requestMap.set(params.requestId, {
                    url: imageUrl,
                    size: 0,
                    interceptedId: interceptionId
                });

                // 放行请求但持续监控数据流
                await tab.Network.continueInterceptedRequest({ interceptionId });

            } catch (err) {
                console.error('拦截处理异常:', err);
                // 确保所有拦截请求最终都被处理
                if (params.interceptionId) {
                    await tab.Network.continueInterceptedRequest({
                        interceptionId: params.interceptionId
                    }).catch(() => { });
                }
            }
        });

        // ================= 配套的流量监控代码 =================
        // 监听数据接收（需要提前启用 tab.Network 域）
        tab.Network.dataReceived(({ requestId, dataLength }) => {
            const entry = requestMap.get(requestId);
            if (entry) {
                entry.size += dataLength;

                // 实时检查：如果已超过阈值立即拦截（激进模式）
                if (entry.size > MAX_IMAGE_SIZE_KB * 1024) {
                    blockedImageUrls.add(entry.url);

                    // 如果请求尚未完成，尝试中止（需要协议支持）
                    tab.Network.continueInterceptedRequest({
                        interceptionId: entry.interceptedId,
                        errorReason: 'BlockedByClient'
                    }).catch(() => { });

                    requestMap.delete(requestId);
                }
            }
        });

        // 请求完成时最终决策
        tab.Network.loadingFinished(({ requestId }) => {
            const entry = requestMap.get(requestId);
            if (!entry) return;

            // 最终大小 = 头部声明大小（如果有效）或实际接收大小
            const finalSize = entry.headerSize > 0 ? entry.headerSize : entry.size;

            if (finalSize > MAX_IMAGE_SIZE_KB * 1024) {
                blockedImageUrls.add(entry.url);
            }

            requestMap.delete(requestId);
        });
    }

    // 电池
    async _setBattery(tab, targetInfo) {
        const { Page } = tab;
        let scriptSource = '';
        switch (this.browserParams.hign.battery) {
            case 2:
                scriptSource = `
        Object.defineProperty(navigator, 'getBattery', {
          value: () => Promise.reject(new Error('Access denied')),
          configurable: false
        });
      `;
                break;
            case 0:
                scriptSource = `
        Object.defineProperty(navigator, 'getBattery', {
          value: () => Promise.resolve({
            level: Math.random(),
            charging: Math.random() > 0.5,
            chargingTime: Math.random() * 1000,
            dischargingTime: Math.random() * 2000,
            addEventListener: () => {}
          }),
          configurable: false
        });
      `;
                break;
            case 1:
                // 无需注入脚本，恢复默认行为
                break;
        }

        if (scriptSource) {
            await Page.addScriptToEvaluateOnNewDocument({ source: scriptSource });
        }

    }

    // Do not track
    async _setDonottrack(tab, targetInfo) {
        let currentHeaders = {}
        await tab.Network.setExtraHTTPHeaders({ headers: {} });

        switch (this.browserParams.hign.donottrack) {
            case 1:
                currentHeaders = { 'DNT': '1' };
                break;
            case 2:
                currentHeaders = { 'DNT': '0' };
                break;
            case 0:
                currentHeaders = {};
                break;
        }

        await tab.Network.setExtraHTTPHeaders({
            headers: currentHeaders
        });
    }

    // 设备内存数
    async _setMemorys(tab, targetInfo) {
        await tab.Page.addScriptToEvaluateOnNewDocument({
            source: `
              Object.defineProperty(navigator, 'deviceMemory', {
                value: ${this.browserParams.hign.memory},
                configurable: false,
                writable: false
              });
            `
        });
        await tab.Page.reload();
    }

    // 硬件并发数
    async _setConcurrency(tab, targetInfo) {
        await tab.Page.addScriptToEvaluateOnNewDocument({
            source: `
              Object.defineProperty(navigator, 'hardwareConcurrency', {
                value: ${this.browserParams.hign.concurrency},
                configurable: false,
                writable: false
              });
            `
        });
        await tab.Page.reload();
    }

    // 媒体设备
    async _setMedia(tab, targetInfo) {
        await tab.send('Browser.grantPermissions', {
            origin: 'https://*/*',
            permissions: ['audioCapture', 'videoCapture'],
        });
    }

    // SpeechVoices
    async _setSpeechVoices(tab, targetInfo) {
        await tab.send('Browser.grantPermissions', {
            origin: 'https://*/*',
            permissions: [],
        });
        await tab.send('Page.addScriptToEvaluateOnNewDocument', {
            source: `
              (function() {
                const originalGetVoices = window.speechSynthesis.getVoices.bind(window.speechSynthesis);
                // 保存原始方法以便恢复
                window.speechSynthesis.__originalGetVoices = originalGetVoices;
                // 自定义语音列表
                window.speechSynthesis.getVoices = () => [
                  { voiceURI: 'Microsoft Huihui - Chinese (Simplified, PRC)', name: 'Microsoft Huihui - Chinese (Simplified, PRC)', lang: 'zh-CN', localService: false, default: true },
                  { voiceURI: 'Microsoft Kangkang - Chinese (Simplified, PRC)', name: 'Microsoft Kangkang - Chinese (Simplified, PRC)', lang: 'zh-CN', localService: false, default: false },
                  { voiceURI: 'Microsoft Yaoyao - Chinese (Simplified, PRC)', name: 'Microsoft Yaoyao - Chinese (Simplified, PRC)', lang: 'zh-CN', localService: false, default: false },
                  { voiceURI: 'Google Deutsch', name: 'Google Deutsch', lang: 'de-DE', localService: true, default: false },
                  { voiceURI: 'Google US English', name: 'Google US English', lang: 'en-US', localService: true, default: false },
                  { voiceURI: 'Google UK English Female', name: 'Google UK English Female', lang: 'en-GB', localService: true, default: false },
                  { voiceURI: 'Google UK English Male', name: 'Google UK English Male', lang: 'en-GB', localService: true, default: false },
                  { voiceURI: 'Google español', name: 'Google español', lang: 'es-ES', localService: true, default: false },
                  { voiceURI: 'Google español de Estados Unidos', name: 'Google español de Estados Unidos', lang: 'es-US', localService: true, default: false },
                  { voiceURI: 'Google français', name: 'Google français', lang: 'fr-FR', localService: true, default: false },
                  { voiceURI: 'Google हिन्दी', name: 'Google हिन्दी', lang: 'hi-IN', localService: true, default: false },
                  { voiceURI: 'Google Bahasa Indonesia', name: 'Google Bahasa Indonesia', lang: 'id-ID', localService: true, default: false },
                  { voiceURI: 'Google italiano', name: 'Google italiano', lang: 'it-IT', localService: true, default: false },
                  { voiceURI: 'Google 日本語', name: 'Google 日本語', lang: 'ja-JP', localService: true, default: false },
                  { voiceURI: 'Google 한국의', name: 'Google 한국의', lang: 'ko-KR', localService: true, default: false },
                  { voiceURI: 'Google Nederlands', name: 'Google Nederlands', lang: 'nl-NL', localService: true, default: false },
                  { voiceURI: 'Google polski', name: 'Google polski', lang: 'pl-PL', localService: true, default: false },
                  { voiceURI: 'Google português do Brasil', name: 'Google português do Brasil', lang: 'pt-BR', localService: true, default: false },
                  { voiceURI: 'Google русский', name: 'Google русский', lang: 'ru-RU', localService: true, default: false },
                  { voiceURI: 'Google 普通话（中国大陆）', name: 'Google 普通话（中国大陆）', lang: 'zh-CN', localService: true, default: false },
                  { voiceURI: 'Google 粤語（香港）', name: 'Google 粤語（香港）', lang: 'zh-HK', localService: true, default: false },
                  { voiceURI: 'Google 國語（臺灣）', name: 'Google 國語（臺灣）', lang: 'zh-TW', localService: true, default: false }
              ];
              })();
            `
        });
        await tab.send('Page.reload');
    }

    async injectGlobalVariable(tab) {
        try {
            const injectionResult = await tab.Runtime.evaluate({
                expression: `window.ENVIRONMENT_PRINT_ID = ${this.browserParams.id}; true;`,
            });
        } catch (error) {
            console.error('操作失败:', error);
        }
    }

    // 创建websocet
    async connectToPlugin() {
        const wss = new WebSocket.Server({ port: 10000 + this.browserParams.id });
        let clients = new Set();

        wss.on('error', (err) => {
            if (err.code === 'EADDRINUSE') {
                console.error('EADDRINUSE');
                wss.close();
            } else {
                console.error('WebSocket error:', err);
            }
        });


        wss.on('connection', (ws) => {
            clients.add(ws);
            // 接收插件消息
            ws.on('message', (data) => {
                let dataJson = JSON.parse(data)
                console.log('getmessage:', data.toString());

                // 广播消息（或定向回复）
                clients.forEach(client => {
                    if (client == ws && client.readyState === WebSocket.OPEN && dataJson.type != 'ping') {
                        let a = {}
                        if (dataJson.type == 'one_status') {
                            a = {
                                type: 'electron_one_status',
                                browserParams: this.browserParams
                            }
                        }
                        console.log(a.type);

                        client.send(JSON.stringify(a));
                    }
                });
            });

            // 断开连接处理
            ws.on('close', () => {
                clients.delete(ws);
                console.log('ws close');
            });
        });
    }

    getfsData(prefsPath, name) {
        const prefsPath2 = path.join(prefsPath, name);
        fs.readFile(prefsPath2, 'utf8', (err, data) => {
            if (err) {
                console.error("无法读取文件:", err);
                return;
            }

            console.log(data);
        });
    }







    async _cleanup() {
        if (this.profilePath) {
            // await fs.remove(this.profilePath).catch(err => {
            //     this.emit('warning', `清理临时目录失败: ${err.message}`)
            // })
        }
        this.process = null
        this.debugPort = 0
        this.profilePath = null
    }
}





export default ChromeController;